package user.zc.config;

import user.zc.config.value.Key;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;


public abstract class MapConfig<T extends Key> implements IConfig<Map<String,T>> {
    protected ValueType type;
    public Map<String, T> data ;
    public MapConfig(ValueType type) {
        this.type = type;
    }

    public Map<String, T> getData() {
        return data;
    }

    public  <T extends Key> Map<String,T> readEntity(String fileName, Class<T> clazz)throws Exception{
        return readConfig(fileName,(line)->type.split(line,clazz));
    }

    private <T extends Key> Map<String,T> readConfig(String fileName, Function<String,T> builder)throws Exception{
        LinkedHashMap<String,T> conf = new LinkedHashMap<>();
        try(BufferedReader bufferedReader = getConfBufferedReader(fileName);){
            String line = null;
            while ((line =bufferedReader.readLine()) != null /*&& !"".equals(line)*/ ) {
                conf.put(line.split(DELIMITER)[0],builder.apply(line));
            }
        }
        return conf;
    }

    @Override
    public  boolean saveOrUpdate(String fileName, Map<String,T> collect)throws Exception{
        //新增是true,修改是false
        File file = getFile(fileName);
        boolean isNew = !file.exists();
        if(file.exists()){
            file.delete();
        }
        try(
                FileWriter fileWriter  = new FileWriter(file);
                BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);){
            for (Map.Entry<String, T> entry : collect.entrySet()) {
                bufferedWriter.write(type.join(entry));
            }
            bufferedWriter.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
        return isNew;
    }

    protected abstract BufferedReader getConfBufferedReader(String fileName)throws Exception;
}
